﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using STKMIS.BLL;
using STKMIS.Model;

namespace STKMIS
{
    public partial class FrmSalesbilling : FrmBase
    {
        public FrmSalesbilling()
        {
            InitializeComponent();
            FrmSalesbillingLoad();
        }

        /// <summary>
        /// 绑定所有的列表
        /// </summary>
        public void FrmSalesbillingLoad()
        {
            BindSupplierList();
            BindProduct();
        }
        /// <summary>
        /// 绑定客户名称
        /// </summary>
        public void BindSupplierList()
        {
            this.cmbSupplierList.DataSource = ProductSupplier.GetProductSupplierListByType("", 1);

            this.cmbSupplierList.DisplayMember = "Name";
            this.cmbSupplierList.ValueMember = "ID";
        }
        /// <summary>
        /// 绑定产品
        /// </summary>
        public void BindProduct()
        {
            DataTable dtProduct = Product.GetProductList("");
            if (dtProduct != null && dtProduct.Rows.Count > 0)
            {
                //初始化列表产品下拉列表
                List<ComboxGridViewColumns> gvProductColumnList = new List<ComboxGridViewColumns>
             {
                  new ComboxGridViewColumns("ProductCode","产品编码"),
                 new ComboxGridViewColumns("ProductName","产品名称",250),
                 new ComboxGridViewColumns("ProductNamePY","产品名称拼音",false),
                 new ComboxGridViewColumns("ProductStandard","标准(型号)"),
                 new ComboxGridViewColumns("ProTypeName","类型"),
                  new ComboxGridViewColumns("ProductID","ID",false)
             };

                this.ProductName.GrvColumnsList = gvProductColumnList;
                this.ProductName.IsShowEvent = true;
                this.ProductName.KeyWordsColumn = "ProductName,ProductNamePY,ProductCode,ProTypeName";
                this.ProductName.DisplayMemberColumn = "ProductName";
                this.ProductName.ValueMemberColumn = "ProductID";
                this.ProductName.dataSource = dtProduct;
            }
            else
            {
                this.dgvPurchaseItem.Enabled = false;
            }
        }
        private void dgvPurchaseItem_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is MultiColumnsCombox)
            {
                (e.Control as MultiColumnsCombox).DoubleClickItemHandler -= new CellsDoubleClickHandler(mcComboxProduct_DoubleClickItemHandler);
                (e.Control as MultiColumnsCombox).DoubleClickItemHandler += new CellsDoubleClickHandler(mcComboxProduct_DoubleClickItemHandler);
            }
            //判断要处理的DataGridViewComboBoxColumn名称，若符合条件，编辑控件被强制转换为TextBox以处理，添加SelectedIndexChanged事件
            if (this.dgvPurchaseItem.CurrentCell.OwningColumn.Name == "PurchaseAmount")
            {
                ((TextBox)e.Control).TextChanged -= new EventHandler(txtPurchaseAmount_TextChanged);
                ((TextBox)e.Control).TextChanged += new EventHandler(txtPurchaseAmount_TextChanged);

                ((TextBox)e.Control).KeyPress -= new KeyPressEventHandler(txtValid_KeyPress);
                ((TextBox)e.Control).KeyPress += new KeyPressEventHandler(txtValid_KeyPress);
            }
            if (this.dgvPurchaseItem.CurrentCell.OwningColumn.Name == "PurchasePrice")
            {
                ((TextBox)e.Control).TextChanged -= new EventHandler(txtPurchasePrice_TextChanged);
                ((TextBox)e.Control).TextChanged += new EventHandler(txtPurchasePrice_TextChanged);

                ((TextBox)e.Control).KeyPress -= new KeyPressEventHandler(txtValid_KeyPress);
                ((TextBox)e.Control).KeyPress += new KeyPressEventHandler(txtValid_KeyPress);
            }

            //if (this.dgvPurchaseItem.CurrentCell.OwningColumn.Name == "Unit")
            //{
            //    ((ComboBox)e.Control).SelectedIndexChanged -= new EventHandler(comboxUnit_SelectedIndexChanged);
            //    ((ComboBox)e.Control).SelectedIndexChanged += new EventHandler(comboxUnit_SelectedIndexChanged);
            //}
        }


        private void txtValid_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox txtStr = sender as TextBox;

            //检测是否已经输入了小数点
            bool IsContainsDot = txtStr.Text.Contains(".");
            if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar != 8) && (e.KeyChar != 46))
            {
                e.Handled = true;
            }
            else if (IsContainsDot && (e.KeyChar == 46)) //如果输入了小数点，并且再次输入
            {
                e.Handled = true;
            }
        }

        private void txtPurchaseAmount_TextChanged(object sender, EventArgs e)
        {
            if (this.dgvPurchaseItem.CurrentCell.OwningColumn.Name == "PurchaseAmount")
            {
                try
                {
                    TextBox txtPurchaseAmount = sender as TextBox;
                    int rowIndex = ((DataGridViewTextBoxEditingControl)(sender)).EditingControlRowIndex;
                    decimal purchasePrice = 0m;

                    //输入是否合法
                    //输入数量
                    if (txtPurchaseAmount.Text != "" && dgvPurchaseItem["ProductNowAmount", rowIndex].Value != null)
                    {
                        decimal Amout = Convert.ToDecimal(txtPurchaseAmount.Text.Trim());
                        //现有的数量
                        decimal NowAmout = decimal.Parse(dgvPurchaseItem["ProductNowAmount", rowIndex].Value.ToString());
                        if (Amout > NowAmout)
                        {
                            MessageBox.Show("库存不足，目前只有" + NowAmout.ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                    }

                    if (dgvPurchaseItem["PurchasePrice", rowIndex].Value == null || dgvPurchaseItem["PurchasePrice", rowIndex].Value.ToString() == "")
                    {
                        purchasePrice = 0m;
                    }
                    else
                    {
                        purchasePrice = dgvPurchaseItem["PurchasePrice", rowIndex].Value.ToString() == "" ? 0m : Convert.ToDecimal(dgvPurchaseItem["PurchasePrice", rowIndex].Value.ToString().Trim());
                    }

                    if (txtPurchaseAmount.Text.Trim() == "" || txtPurchaseAmount.Text.Trim() == ".")
                    {
                        txtPurchaseAmount.Text = "0";
                    }
                    this.dgvPurchaseItem["PurchaseMoney", rowIndex].Value = (purchasePrice * Convert.ToDecimal(txtPurchaseAmount.Text.Trim())).ToString();
                    //刷新总价
                    PurchaseSumMoney();
                }
                catch (Exception)
                {
                    MessageBox.Show("输入不合法", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //throw;
                    //记录日志
                    //
                    return;
                }

            }
        }
        private void PurchaseSumMoney()
        {
            decimal sumMoney = 0m;
            foreach (DataGridViewRow dgvr in dgvPurchaseItem.Rows)
            {
                if (dgvr.Cells["PurchaseMoney"].Value != null)
                {
                    decimal rowsum = dgvr.Cells["PurchaseMoney"].Value.ToString() == "" ? 0m : Convert.ToDecimal(dgvr.Cells["PurchaseMoney"].Value.ToString());
                    sumMoney = sumMoney + rowsum;
                }
            }
            txtSaleSum.Text = sumMoney.ToString();
        }
        private void txtPurchasePrice_TextChanged(object sender, EventArgs e)
        {
            if (this.dgvPurchaseItem.CurrentCell.OwningColumn.Name == "PurchasePrice")
            {
                TextBox txtPurchasePrice = sender as TextBox;
                int rowIndex = ((DataGridViewTextBoxEditingControl)(sender)).EditingControlRowIndex;
                decimal purchaseAmount = 0m;
                if (dgvPurchaseItem["PurchaseAmount", rowIndex].Value == null || dgvPurchaseItem["PurchaseAmount", rowIndex].Value.ToString() == "")
                {
                    purchaseAmount = 0m;
                }
                else
                {
                    purchaseAmount = dgvPurchaseItem["PurchaseAmount", rowIndex].Value.ToString() == "" ? 0m : Convert.ToDecimal(dgvPurchaseItem["PurchaseAmount", rowIndex].Value.ToString().Trim());
                }

                if (txtPurchasePrice.Text.Trim() == "" || txtPurchasePrice.Text.Trim() == ".")
                {
                    txtPurchasePrice.Text = "0";
                }
                this.dgvPurchaseItem["PurchaseMoney", rowIndex].Value = (purchaseAmount * Convert.ToDecimal(txtPurchasePrice.Text.Trim())).ToString();
                PurchaseSumMoney();
            }
        }
        private void mcComboxProduct_DoubleClickItemHandler(object sender, DoubleClickEventArgs e)
        {
            DataGridViewRow row = e.Value as DataGridViewRow;
            this.dgvPurchaseItem[1, e.RowIndex].Value = row.Cells["ProductName"].Value.ToString();
            this.dgvPurchaseItem[0, e.RowIndex].Value = row.Cells["ProductStandard"].Value.ToString();

            DataTable dt = STKMIS.BLL.Sale.GetProductAndUnit(int.Parse(row.Cells["ProductID"].Value.ToString()));
            this.dgvPurchaseItem["Unit", e.RowIndex].Value = dt.Rows[0]["ProUnitName"].ToString();

            this.dgvPurchaseItem["UnitId", e.RowIndex].Value = dt.Rows[0]["ProUnitID"].ToString();

            this.dgvPurchaseItem["PurchasePrice1", e.RowIndex].Value = dt.Rows[0]["PurchasePrice"].ToString();
            this.dgvPurchaseItem["ProductNowAmount", e.RowIndex].Value = dt.Rows[0]["ProductNowAmount"].ToString();

        }


        /// <summary>
        /// 保存销售开单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //主表属性赋值
                SaleModel saleInfo = new SaleModel();

                saleInfo.ProductSupplierID = int.Parse(this.cmbSupplierList.SelectedValue.ToString());
                //采购金额
                decimal PurchaseSumMoney = 0;
                for (int i = 0; i < this.dgvPurchaseItem.Rows.Count; i++)
                {
                    if (dgvPurchaseItem.Rows[i].Cells["PurchasePrice1"].ToString() != "" && dgvPurchaseItem.Rows[i].Cells["PurchaseAmount"].ToString() != "")
                    {
                        PurchaseSumMoney += decimal.Parse(dgvPurchaseItem.Rows[i].Cells["PurchasePrice1"].ToString()) * decimal.Parse(dgvPurchaseItem.Rows[i].Cells["PurchaseAmount"].ToString());
                    }
                }
                saleInfo.PurchaseSumMoney = PurchaseSumMoney;

                //销售金额
                saleInfo.SaleSumMoney = decimal.Parse(this.txtSaleSum.Text.ToString());
                //利润
                saleInfo.SaleSumProfit = saleInfo.SaleSumMoney - saleInfo.PurchaseSumMoney;
                saleInfo.SaleTime = DateTime.Now;
                //销售人员 从session 读
                saleInfo.SaleUserID = 0;

                saleInfo.SaleRemark = this.txtRemark.Text.ToString();

                //子表属性赋值
                List<SaleItemModel> lstSaleItem = new List<SaleItemModel>();
                for (int i = 0; i < this.dgvPurchaseItem.Rows.Count; i++)
                {
                    SaleItemModel saleItem = new SaleItemModel();
                    if (dgvPurchaseItem.Rows[i].Cells["UnitID"].ToString() != "")
                    {
                        saleItem.ProductsAndUnitID = int.Parse(dgvPurchaseItem.Rows[i].Cells["UnitID"].ToString());

                        saleItem.SaleAmount = decimal.Parse(dgvPurchaseItem.Rows[i].Cells["PurchaseAmount"].ToString());
                        saleItem.SalePrice = decimal.Parse(dgvPurchaseItem.Rows[i].Cells["PurchasePrice"].ToString());
                        saleItem.SaleMoney = decimal.Parse(dgvPurchaseItem.Rows[i].Cells["PurchaseMoney"].ToString());
                        saleItem.SaleProfit = saleItem.SalePrice - decimal.Parse(dgvPurchaseItem.Rows[i].Cells["PurchasePrice1"].ToString());
                    }
                    lstSaleItem.Add(saleItem);
                }
                string msg = "";
                if (Sale.InsertSaleSaleItem(saleInfo, lstSaleItem, ref msg))
                {
                    //插入成功
                }
                else
                {
                    //插入失败
                }

            }
            catch (Exception)
            {

                throw;
            }

        }

        /// <summary>
        /// 获取销售单号
        /// </summary>
        /// <returns></returns>
        public string GetSerialNumber(string BillType, int IsNeedDate, ref string msg)
        {
            string SerialNumber = "";
            SerialNumber = Common.GetSerialNumber(BillType, IsNeedDate, ref msg);
            return SerialNumber;
        }

        /// <summary>
        /// 获取产品信息
        /// </summary>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        public DataTable GetProductList(string keyWord)
        {
            DataTable dt = new DataTable(keyWord);
            dt = Product.GetProductList(keyWord);
            return dt;
        }

        /// <summary>
        /// 获取单位
        /// </summary>
        /// <returns></returns>
        public DataTable GetProductUnitList(string keyWord)
        {
            DataTable dt = ProductUnit.GetProductUnitList(keyWord);
            return dt;
        }
        private void btnAddUser_Click(object sender, EventArgs e)
        {
            //跳转到新增客户界面
        }
    }
}
